<template>
  <el-dialog
    :visible.sync="dialogShow"
    width="950px"
    :title="!isAdd ? '编辑功能' : '新增功能'"
    :before-close="cancelEdit"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <el-form
      v-if="dialogShow"
      class="model-form"
      :rules="rules"
      label-width="120px"
      :model="modelForm"
      ref="modelFormRef"
    >
      <el-form-item label="功能类型">
        <el-radio-group :disabled="!isAdd" v-model="modelForm.type" size="mini">
          <el-radio-button label="property">属性</el-radio-button>
          <el-radio-button label="service">服务</el-radio-button>
          <el-radio-button label="event">事件</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <div v-if="isSelectType('property')">
        <property-model
          ref="propertyModelRef"
          :property="modelForm.raw"
          :enumItems="enumItems"
          :boolItem="boolItem"
          :isProperty="true"
          :isUpdate="!isAdd"
          @updateModelForm="updateModelForm"
        />
      </div>
      <div v-if="isSelectType('service')">
        <div class="type-service">
          <el-form-item label="名称" prop="name" size="small">
            <el-input
              v-model="modelForm.name"
              auto-complete="off"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item label="标识符" prop="identifier" size="small">
            <el-input
              v-model="modelForm.identifier"
              auto-complete="off"
              maxlength="30"
              :disabled="!isAdd"
            />
          </el-form-item>
          <el-form-item label="输入参数" prop="inputData" size="small">
            <ModelParams
              :modelParams="modelForm.raw.inputData"
              :isService="true"
              :is-update="!isAdd"
            />
          </el-form-item>
          <el-form-item label="输出参数" prop="outputData" size="small">
            <ModelParams
              :modelParams="modelForm.raw.outputData"
              :isService="true"
              :is-update="!isAdd"
            />
          </el-form-item>
        </div>
      </div>
      <div v-if="isSelectType('event')">
        <div class="type-event">
          <el-form-item label="名称" prop="name" size="small">
            <el-input
              v-model="modelForm.name"
              auto-complete="off"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item label="标识符" prop="identifier" size="small">
            <el-input
              v-model="modelForm.identifier"
              auto-complete="off"
              maxlength="30"
            />
          </el-form-item>
          <el-form-item label="输出参数" prop="outputData" size="small">
            <ModelParams :modelParams="modelForm.raw.outputData" />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelEdit" class="cancel-button"
        >取 消</el-button
      >
      <el-button
        size="small"
        @click="saveThingModel"
        v-preventReClick="1000"
        class="confirm-button"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { reqThingModel } from "@/api/rule";
import { ParseProperty } from "@/utils/util.ts";
import PropertyModel from "./PropertyModel.vue";
import ModelParams from "./ModelParams.vue";
import { validateidentifier } from "@utils/validate";

export default {
  props: {
    deviceType: {
      type: String,
      default: "",
    },
    model: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    PropertyModel,
    ModelParams,
  },
  data() {
    return {
      isAdd: true,
      data: {},
      dialogShow: false,
      modelForm: {},
      modelType: "1",
      boolItem: {},
      enumItems: [{}],
      scriptRules: {
        model: [
          { required: true, message: "设备型号不能为空", trigger: "blur" },
        ],
        script: [
          { required: true, message: "脚本内容不能为空", trigger: "blur" },
        ],
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        identifier: [
          { required: true, message: "请输入标识符", trigger: "blur" },
          { validator: validateidentifier },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  methods: {
    updateModelForm(data) {
      console.log(data, "data");
      // console.log(data,'111');
      // this.modelForm.raw = data;
    },
    saveThingModel() {
      const fun =
        this.modelForm.type === "property"
          ? this.$refs.propertyModelRef.validate
          : this.$refs.modelFormRef.validate;
      fun().then((valid) => {
        if (valid) {
          if (this.isAdd) {
            if (this.modelForm.type === "property") {
              if (this.model.properties) {
                // 删除旧的
                const idx = this.model.properties.findIndex(
                  (p) => p.identifier === this.modelForm.raw.identifier
                );
                if (idx >= 0) {
                  this.model.properties.splice(idx, 1);
                }
              } else {
                this.model.properties = [];
              }
              this.model.properties.push(this.newProperty());
            } else if (this.modelForm.type === "service") {
              if (this.model.services) {
                // 删除旧的
                const idx = this.model.services.findIndex(
                  (p) => p.identifier === this.modelForm.raw.identifier
                );
                if (idx >= 0) {
                  this.model.services.splice(idx, 1);
                }
              } else {
                this.model.services = [];
              }
              this.model.services.push({
                identifier: this.modelForm.identifier,
                name: this.modelForm.name,
                inputData: this.modelForm.raw.inputData,
                outputData: this.modelForm.raw.outputData,
              });
            } else if (this.modelForm.type === "event") {
              if (this.model.events) {
                // 删除旧的
                const idx = this.model.events.findIndex(
                  (p) => p.identifier === this.modelForm.raw.identifier
                );
                if (idx >= 0) {
                  this.model.events.splice(idx, 1);
                }
              } else {
                this.model.events = [];
              }
              this.model.events.push({
                identifier: this.modelForm.identifier,
                name: this.modelForm.name,
                outputData: this.modelForm.raw.outputData,
              });
            }
          } else {
            if (this.modelForm.type === "property") {
              let prop = this.newProperty();
              for (let i = 0; i < this.model.properties.length; i++) {
                if (this.model.properties[i].identifier === prop.identifier) {
                  this.model.properties[i] = prop;
                }
              }
            } else if (this.modelForm.type === "service") {
              this.model.services.forEach((s) => {
                if (s.identifier === this.modelForm.identifier) {
                  s.identifier = this.modelForm.identifier;
                  s.name = this.modelForm.name;
                  s.inputData = this.modelForm.raw.inputData;
                  s.outputData = this.modelForm.raw.outputData;
                }
              });
            } else if (this.modelForm.type === "event") {
              this.model.events.forEach((s) => {
                if (s.identifier === this.modelForm.identifier) {
                  s.identifier = this.modelForm.identifier;
                  s.name = this.modelForm.name;
                  s.outputData = this.modelForm.raw.outputData;
                }
              });
            }
          }
          this.submitThingModelChange();
        }
      });
    },
    async submitThingModelChange() {
      if (this.model) {
        this.model.services = this.model.services || [];
        this.model.properties = this.model.properties || [];
        this.model.events = this.model.events || [];
      }
      console.log(this.model, "this.model111");

      let res = await reqThingModel({
        productKey: this.deviceType,
        model: JSON.stringify(this.model),
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      console.log(res);
      if (this.isAdd) {
        this.$modal.notifySuccess("新增成功");
      } else {
        this.$modal.notifySuccess("编辑成功");
      }
      this.dialogShow = false;
      this.cancelEdit();
      this.$emit("updateObjectModel");
    },
    openDialog(row, prop) {
      console.log("111", row, prop);
      if (row) {
        this.modelForm = row;
        this.isAdd = false;
        this.modelType =
          row.model?.endsWith && row.model.endsWith("_default") ? "1" : "2";
        if (prop.enumItems) this.enumItems = prop.enumItems;
        if (prop.boolItem) this.boolItem = prop.boolItem;
      } else {
        // 新增
        this.isAdd = true;
        this.modelForm = {
          type: "property",
          identifier: "",
          name: "",
          raw: {
            name: "",
            identifier: "",
            description: "",
            accessMode: "rw",
            type: "property",
            dataType: {
              specs: {},
            },
            inputData: [],
            outputData: [],
            enumItems: [],
            boolItem: {
              _true: "",
              _false: "",
            },
          },
        };
      }
      this.model = this.model;
      this.dialogShow = true;
    },
    isSelectType(type) {
      return type === this.modelForm.type;
    },
    newProperty() {
      return ParseProperty(this.modelForm.raw, this.enumItems, this.boolItem);
    },

    cancelEdit() {
      this.dialogShow = false;
    },
  },
  created() {},
  mounted() {},
};
</script>

<style lang="less" scoped>
@import url("../../../../common.less");

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  color: #fff;
  background-color: #7367f0;
  border-color: #7367f0;
  box-shadow: -1px 0 0 0 #7367f0;
}

.model-form {
  color: @primaryThemeTxtColor2;
}

// 单选按钮
::v-deep .el-radio {
  color: @primaryThemeTxtColor2;
}

::v-deep .el-radio__input.is-checked + .el-radio__label {
  color: #7367f0;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #7367f0;
  background: #7367f0;
}

::v-deep .el-tabs--border-card {
  border: 1px solid #434968 !important;
}

// 单选按钮---------
</style>
